package com.banciyuan.bcywebview.biz.detail.comment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailType;


public class DetailCommentActivity extends BaseActivity implements View.OnClickListener, BaseWatcher {

    private PullToRefreshListView mRefreshListView;
    private ListView mListView;
    private String commentId;
    private TextView tvTotolCounts;
    private DetailComment commentDetail;
    private List<DetailComment> mReplyCommentList = new ArrayList<>();
    private int page = 1;
    private DetailCommentAdapter mDetailCommentAdapter;
    private DetailType mDetailType;
    private String mWorkAuthorUid;
    private boolean loading = false;
    private boolean end_flag = false;
    private boolean from_push = false;
    private ProgressbarHelper mProgressbarHelper;
    private CommentHelper commentHelper;
    private BaseViewComment baseViewComment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comments_layout);
        initArgs();
        initActionbar();
        initUi();
        initProgressbar();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        commentId = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        mDetailType = (DetailType) intent.getSerializableExtra(gotoUtil.INTENT_VALUE_TWO);
        from_push = intent.getBooleanExtra(gotoUtil.INTENT_VALUE_THREE, false);
        commentHelper = new CommentHelper(this, mDetailType);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    mProgressbarHelper.onLoading();
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        tvTotolCounts = ((TextView) findViewById(R.id.base_action_bar_title));
        if (from_push) {
            TextView goDetail = ((TextView) findViewById(R.id.base_action_bar_home_text));
            goDetail.setText(getString(R.string.goto_detail));
            goDetail.setOnClickListener(this);
        }
        findViewById(R.id.base_action_bar_home).setOnClickListener(this);
    }

    @Override
    protected void initUi() {
        mRefreshListView = (PullToRefreshListView) findViewById(R.id.refresh_lv);
        mListView = mRefreshListView.getRefreshableView();
        View header = LayoutInflater.from(this).inflate(R.layout.comment_detail_item, mListView, false);
        baseViewComment = new BaseViewComment(header);
        header.findViewById(R.id.iv_shark).setVisibility(View.VISIBLE);
        header.findViewById(R.id.ll_comments_container).setBackgroundColor(getResources().getColor(R.color.content_background));
        mListView.addHeaderView(header);
        View footer = new View(this);
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, UIUtils.dip2px(60, this));
        footer.setLayoutParams(layoutParams);
        mListView.addFooterView(footer);
        findViewById(R.id.rl_publish).setOnClickListener(this);

    }

    @Override
    protected void initAction() {
        mRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading) {
                    if (!end_flag) {
                        loading = true;
                        page++;
                        getReplyData();
                    }
                }
            }
        });
        mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loading = true;
                end_flag = false;
                page = 1;
                getReplyData();
            }
        });
    }

    @Override
    protected void initData() {
        getReplyData();
        getSingleCommentData();
    }

    private void getSingleCommentData() {
        commentHelper.getSingleCommentData(commentId, new IGetComment() {
            @Override
            public void getSucc(String json) {
                try {
                    Gson gson = new Gson();
                    JSONObject result = new JSONObject(json);
                    switch (result.getInt(HttpUtils.UPLOAD_STATUS)) {
                        case 1:
                            onCommentSuccess(gson, result);
                            break;
                        case MyConstants.COMMENT_NOTEXIT:
                            onCommentDelete();
                            break;
                        case MyConstants.DETAIL_NOTEXIT:
                            onDetailDelete();
                            break;
                        default:
                            onError();
                            break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    onError();
                }
            }

            @Override
            public void getFail() {
                onError();
            }
        });
    }

    private void onCommentSuccess(Gson gson, JSONObject result) throws Exception {
        commentDetail = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), DetailComment.class);
        CommentHelper.processDetailComment(commentDetail);
        mWorkAuthorUid = commentDetail.getPost().getUid();
        baseViewComment.setCommonIds(mWorkAuthorUid, commentDetail.getUid());
        baseViewComment.setData(-1, commentDetail, DetailCommentActivity.this, true, mDetailType, false);
        tvTotolCounts.setText(String.format(getString(R.string.reply_count_format), commentDetail.getComments_count()));
        createDetailComment();
        mProgressbarHelper.onSuccess();
    }

    private void onCommentDelete() {
        mProgressbarHelper.onFailed(getString(R.string.comment_has_been_delete));
    }

    private void onDetailDelete() {
        mProgressbarHelper.onFailed(getString(R.string.detail_has_been_delete));
    }

    private void createDetailComment() {
        if (null == mDetailCommentAdapter) {
            mDetailCommentAdapter = new DetailCommentAdapter(DetailCommentActivity.this, mReplyCommentList, mDetailType, commentDetail.getId(), mWorkAuthorUid, commentDetail.getUid());
            mListView.setAdapter(mDetailCommentAdapter);
        }
    }

    private void getReplyData() {
        commentHelper.getReplyData(commentId, page, new IGetComment() {
            @Override
            public void getSucc(String json) {
                if (StatusCodeUtils.dealStatusCode(json, DetailCommentActivity.this)) {
                    try {
                        Gson gson = new Gson();
                        List<DetailComment> templist = gson.fromJson(new JSONObject(json).getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<DetailComment>>() {
                        }.getType());
                        if (templist.isEmpty())
                            end_flag = true;
                        processCommentsData(templist);
                        onSuccess();
                    } catch (Exception e) {
                        e.printStackTrace();
                        onError();
                    }
                } else {
                    onError();
                }
            }

            @Override
            public void getFail() {
                onError();
            }
        });
    }

    private void onSuccess() {
        mRefreshListView.onRefreshComplete();
        loading = false;
    }

    private void onError() {
        tvTotolCounts.setText(String.format(getString(R.string.reply_count_format), 0));
        mProgressbarHelper.onFailed();
        mRefreshListView.onRefreshComplete();
        loading = false;
    }

    private void processCommentsData(List<DetailComment> templist) {
        CommentHelper.processTemList(templist);
        if (page == 1) {
            mReplyCommentList.clear();
        }
        mReplyCommentList.addAll(templist);
        if (null != mDetailCommentAdapter) {
            mDetailCommentAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_publish:
                doReply();
                break;
            case R.id.base_action_bar_home:
                finish();
                break;
            case R.id.base_action_bar_home_text:
                switch (mDetailType.getTimelineType()) {
                    case TimelineFactory.TIMELINE_TYPE_COSER:
                        DetailDataHelper.gotoCosDetail(this, mDetailType.getRp_id(), mDetailType.getCp_id(), false);
                        break;
                    case TimelineFactory.TIMELINE_TYPE_ILLUST:
                        DetailDataHelper.gotoDrawerDetail(this, mDetailType.getRp_id(), mDetailType.getDp_id(), false);
                        break;
                    case TimelineFactory.TIMELINE_TYPE_GROUP:
                        DetailDataHelper.gotoGroupDetail(this, mDetailType.getGid(), mDetailType.getPost_id(), false);
                        break;
                    case TimelineFactory.TIMELINE_TYPE_DAILY:
                        DetailDataHelper.gotoDailyDetail(this, mDetailType.getUd_id(), false);
                        break;
                    case TimelineFactory.TIMELINE_TYPE_WRITER:
                        DetailDataHelper.gotoWriterDetail(this, mDetailType.getRp_id(), mDetailType.getWp_id(), false);
                        break;
                }
                break;
        }
    }

    private void doReply() {
        Intent intent = new Intent(this, EditActivity.class);
        intent.putExtra(CommentConstants.COMMENT_TYPE, 2);
        intent.putExtra(CommentConstants.UNAME, commentDetail.getUname());
        intent.putExtra(CommentConstants.CONTENT, commentDetail.getContent());
        intent.putExtra(CommentConstants.SHOW_CHARGE, false);
        intent.putExtra(CommentConstants.COMMENT_ID, commentDetail.getId());
        intent.putExtra(CommentConstants.COMMENT_POS, -1);
        DetailDataHelper.putBaseDetailValue(intent, mDetailType);
        startActivityForResult(intent, CommentConstants.GO_REPLY);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommentConstants.GO_REPLY && resultCode == EditActivity.END_ADD) {
            dealAddReply(data);
        }
    }

    private void dealAddReply(Intent data) {
        DetailComment detailComment = (DetailComment) data.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        CommentHelper.processDetailComment(detailComment);
        if (null != mReplyCommentList)
            mReplyCommentList.add(0, detailComment);
        mDetailCommentAdapter.notifyDataSetChanged();
        mListView.setSelection(0);
        tvTotolCounts.setText(String.format(getString(R.string.reply_count_format), mReplyCommentList.size()));
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(ComplexDetailActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(ComplexDetailActivity.class);
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.DELELE_REPLY_EVENT:
                if (object instanceof DetailComment)
                    mReplyCommentList.remove(object);
                mDetailCommentAdapter.notifyDataSetChanged();
                tvTotolCounts.setText(String.format(getString(R.string.reply_count_format), mReplyCommentList.size()));
                break;
            case BaseObserver.LIKE_COMMENT_EVENT:
                if ((Integer) object == -1) {
                    likeComment();
                } else {
                    likeReply((Integer) object);
                }
                break;
            case BaseObserver.DISLIKE_COMMENT_EVENT:
                if ((Integer) object == -1) {
                    disLikeComment();
                } else {
                    disLikeReply((Integer) object);
                }
                break;
            case BaseObserver.DELELE_COMMENT_EVENT:
                if ((Integer) object == -1) {
                    tvTotolCounts.setText(String.format(getString(R.string.reply_count_format), 0));
                    mProgressbarHelper.onLoading();
                    mProgressbarHelper.onFailed(getString(R.string.comment_has_been_delete));

                }
                break;
        }
    }

    private void likeReply(int position) {
        if (null != mDetailCommentAdapter && position >= 0 && position < mReplyCommentList.size()) {
            DetailComment detailComment = mReplyCommentList.get(position);
            detailComment.setHave_ding(true);
            detailComment.setDing_num(detailComment.getDing_num() + 1);
            mDetailCommentAdapter.notifyDataSetChanged();
        }
    }

    private void disLikeReply(int position) {
        if (null != mDetailCommentAdapter && position >= 0 && position < mReplyCommentList.size()) {
            DetailComment detailComment = mReplyCommentList.get(position);
            detailComment.setHave_ding(false);
            detailComment.setDing_num(detailComment.getDing_num() - 1);
            mDetailCommentAdapter.notifyDataSetChanged();
        }
    }

    private void disLikeComment() {
        commentDetail.setHave_ding(false);
        commentDetail.setDing_num(commentDetail.getDing_num() - 1);
        baseViewComment.setPraise(commentDetail, this);
    }

    private void likeComment() {
        commentDetail.setHave_ding(true);
        commentDetail.setDing_num(commentDetail.getDing_num() + 1);
        baseViewComment.setPraise(commentDetail, this);
    }
}
